<?php
/**
 * Created by PhpStorm.
 * User: lx
 * Date: 2020/1/6
 * Time: 12:01
 */
namespace app\command\controller;

use think\Controller;
use think\facade\Session;
use think\cache\driver\Redis;

/**
 * 微信公共类
 * Class WxCommon
 * @package app\command\controller
 */
class WxCommon extends Controller
{
    private $WxTokenUrl = "https://api.weixin.qq.com/cgi-bin/token"; // access_token url
    private $UnionIdUrl = "https://api.weixin.qq.com/wxa/getpaidunionid"; // unionid url
    /**
     * 获取wx accessToken
     * @return 返回的|mixed
     */
    public function getAccessToken(){
        $redis = new Redis();
        if($redis->has('accessToken.accessToken')){
            return $redis->get('accessToken.accessToken');
        }
        $appid = config("apiadmin.APPID");
        $secret = config("apiadmin.APPSECRET");
        $url = $this->WxTokenUrl."?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $tokenRequestJson = (new MyCurl())->curlRequest($url);
        $tokenRequest = json_decode($tokenRequestJson,true);
        if($tokenRequest['errcode'] !== 0){ //未成功
            return ['code' => 2,'data' => "accessToken获取失败:".$tokenRequest,];
        }
        $this->accessToken = $tokenRequest;
        $redis->set("accessToken",$tokenRequest,7200);
        $redis->set("accessToken.accessToken",$tokenRequest['accessToken'],7200);
        return $tokenRequest['accessToken'];
    }

    /**
     * UnionID获取
     * @param string $openID   用户openud
     * @param string $transaction_id    微信支付订单号
     * @param string $mch_id    微信支付分配的商户号，和商户订单号配合使用
     * @param string $out_trade_no  微信支付商户订单号，和商户号配合使用
     * @return array
     */
    public function getUserUnionId($openID, $transaction_id = "", $mch_id = "", $out_trade_no = ""){
        $access_token = $this->getAccessToken();
        $requestUrl = $this->UnionIdUrl."?access_token=".$access_token."&openid=".$openID;
        $resData = (new MyCurl())->curlRequest($requestUrl);
        $resDataArr = json_decode($resData,true);
        if($resDataArr['errcode'] !== 0){
            return ['code' => 2,'data'=>$resDataArr];
        }
        return $resDataArr['unionid'];
    }
    /**
     * @todo
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData( $encryptedData, $iv, &$data )
    {
        $sessionKey = $this->request->param("sessionKey");
        if (strlen($sessionKey) != 24) {
            return $this->error();
        }
        $aesKey=base64_decode($sessionKey);


        if (strlen($iv) != 24) {
            return ErrorCode::$IllegalIv;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return ErrorCode::$IllegalBuffer;
        }
        if( $dataObj->watermark->appid != $this->appid )
        {
            return ErrorCode::$IllegalBuffer;
        }
        $data = $result;
        return ErrorCode::$OK;
    }
}